//
//  PostDataController.m
//  FlowingData
//
//  Created by NIMESH DESAI on 10/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PostDataController.h"

@implementation PostDataController

@synthesize statusLabel;
@synthesize inputField;
@synthesize scrollView;
@synthesize mainView;
@synthesize tableView;

#pragma mark
#pragma mark NSURL CONNECTION delegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse *)response;
	NSLog(@"didReceiveResponse response = %@", httpResponse);
	statusCode = [httpResponse statusCode];
	NSLog(@"headers = %@", [httpResponse allHeaderFields]);
	//[connection release];
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
	NSLog(@"didReceiveData - data = %@", data);
	NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	NSLog(@"didReceiveData - data to string = %@", string);
	if( statusCode == 200 )
	{
		if( [string isEqualToString:@"Error - Require subject and predicate."] == YES )
		{
			NSString* length = [[NSString alloc] initWithFormat:@"%@", inputField.text];
			if( [length length] != 0 )
				statusLabel.text = @"Enter username";
			else
				statusLabel.text = @"Enter Predicate";
			[length release];
		}			
		else
			statusLabel.text = string;
	}
	[string release];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	NSLog(@"connection did finish loading");
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[connection release];
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[connection release];
	NSLog(@"didFailWithError error = %@", error);
}

#pragma mark -

#pragma mark TEXT FIELD delegate methods

- (BOOL) textFieldShouldReturn:(UITextField*)textField
{
	[textField resignFirstResponder];
	return YES;
}

-(IBAction)textFieldDoneEditing:(id)sender
{
	[sender resignFirstResponder];
}

- (void)registerForKeyboardNotifications
{
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasShown:)
												 name:UIKeyboardDidShowNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasHidden:)
												 name:UIKeyboardDidHideNotification object:nil];
}

- (void) keyboardWasShown:(NSNotification*)aNotification
{
	if( keyboardShown )
		return;
	NSDictionary* info = [aNotification userInfo];
	
	NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
	
	CGRect viewFrame = [scrollView frame];
	viewFrame.size.height -= keyboardSize.height;
	scrollView.frame = viewFrame;
	
	CGRect textFieldRect = [inputField frame];
	[scrollView scrollRectToVisible:textFieldRect animated:YES];
	keyboardShown = YES;
}

- (void)keyboardWasHidden:(NSNotification*)aNotification
{
	NSDictionary* info = [aNotification userInfo];
	
	// Get the size of the keyboard.
	NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
	
	// Reset the height of the scroll view to its original value
	CGRect viewFrame = [scrollView frame];
	viewFrame.size.height += keyboardSize.height;
	scrollView.frame = viewFrame;
	[scrollView scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:YES];
	keyboardShown = NO;
}

#pragma mark -

#pragma mark CONNECTION methods

- (IBAction)postData:(id)sender
{
	[self textFieldShouldReturn:inputField];
	NSString* input = [[NSString alloc] initWithFormat:@"OK - %@", inputField.text];
	
	//NSLog(@"%@", input);
	
	NSArray* temp = [input componentsSeparatedByString:@" "];
	
	if( [temp count] < 4 )
	{
		NSString* temp1 =	[[NSString alloc] initWithFormat: @"%@",[temp objectAtIndex:2]];
		appDelegate =		[[UIApplication sharedApplication] delegate];
		NSString* user =	[[NSString alloc] initWithFormat:@"%@", appDelegate.userName];		
		NSString* pass =	[[NSString alloc] initWithFormat:@"%@", appDelegate.passWord];
		urlString =			[[NSString alloc] initWithFormat:
							@"http://www.ist.rit.edu/~acjvks/rmail/admin/add_triple.php?s=%@&p=%@&o=-&password=%@",
							 user, temp1, pass];
		NSLog(@"%@", urlString);
		
		NSURL* url = [NSURL URLWithString:urlString];
		[urlString release];
		NSURLRequest* request =	[NSURLRequest requestWithURL:url
								cachePolicy:NSURLRequestUseProtocolCachePolicy
								timeoutInterval:10.0];
		NSURLConnection* connection =	[[NSURLConnection alloc] initWithRequest:request delegate:self];
		if( connection )
			[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];	
		
		[temp1 release];
		[user release];
		[pass release];
			
	}
	else
	{
		//NSLog(@"%d", [temp count]);
		//NSLog(@"%@", [temp objectAtIndex:2]);
		//NSLog(@"%@", [temp objectAtIndex:3]);
		
		NSString* temp1 = [[NSString alloc] initWithFormat: @"%@",[temp objectAtIndex:2]];
		NSString* temp2 = [[NSString alloc] initWithFormat: @"%@", [temp objectAtIndex:3]];
		appDelegate = [[UIApplication sharedApplication] delegate];
		NSString* user = [[NSString alloc] initWithFormat:@"%@", appDelegate.userName];

		NSString* pass = [[NSString alloc] initWithFormat:@"%@", appDelegate.passWord];
		urlString = [[NSString alloc] initWithFormat:
					 @"http://www.ist.rit.edu/~acjvks/rmail/admin/add_triple.php?s=%@&p=%@&o=%@&password=%@",
					 user, temp1, temp2, pass];
		NSLog(@"%@", urlString);
	
		NSURL* url = [NSURL URLWithString:urlString];
		[urlString release];
		NSURLRequest* request = [NSURLRequest requestWithURL:url
										  cachePolicy:NSURLRequestUseProtocolCachePolicy
										 timeoutInterval:10.0];
		NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
		if( connection )
			[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];	
	
		[temp1 release];
		[temp2 release];
		[user release];
		[pass release];
	}
	[input release];
}

#pragma mark -

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

#pragma mark View Did load

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{	
    [super viewDidLoad];
	tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, 320, 300) style:UITableViewStyleGrouped];
	[tableView setDelegate:self];
	[tableView setDataSource:self];
	[tableView setBackgroundColor:[UIColor clearColor]];
	NSString* path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
	tableData = [[NSMutableArray alloc] initWithContentsOfFile:path];
	keyboardShown = false;
	appDelegate = [[UIApplication sharedApplication] delegate];
	statusLabel.text = @"Your status will appear here";
	scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
	scrollView.clipsToBounds = YES;
	scrollView.scrollEnabled = YES;
	scrollView.pagingEnabled = NO;
	[scrollView setContentSize:CGSizeMake(270, 380)];
	[scrollView addSubview:tableView];
	[scrollView addSubview:mainView];
	[self registerForKeyboardNotifications];
}

#pragma mark -
#pragma mark table view delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	NSLog(@"table data count = %d", [tableData count]);
    return [tableData count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)table_View cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [table_View dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
	{
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	NSUInteger row = [indexPath row];
	cell.textLabel.text = [[tableData objectAtIndex:row] objectForKey:@"name"];
	cell.textLabel.font = [UIFont italicSystemFontOfSize:20];
	cell.showsReorderControl = YES;
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	
    return cell;
}


- (void)tableView:(UITableView *)table_View didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell* cell = [table_View cellForRowAtIndexPath:indexPath];
	NSString* temp = cell.textLabel.text;
	//[table_View deselectRowAtIndexPath:indexPath animated:YES];
	[self _createDetailView:temp];
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (editingStyle == UITableViewCellEditingStyleDelete)
	{
		[smurfArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else 
		if (editingStyle == UITableViewCellEditingStyleInsert) 
		{
			// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
		}   
}


// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
	NSDictionary* smurf = [[smurfArray objectAtIndex:[fromIndexPath row]] retain];
	
	[smurfArray removeObjectAtIndex:[fromIndexPath row]];
	[smurfArray insertObject:smurf atIndex:[toIndexPath row]];
	[smurf release];
}
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

-(void)tableView:(UITableView*)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath
{
	//[self _createDetailView:indexPath.row];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

-(void) _createDetailView:(NSString*)temp
{
	inputField.text = temp;
	[inputField becomeFirstResponder];
}

#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning 
{
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload 
{
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc
{
	[tableView release];
	[tableData release];
    [super dealloc];
}

#pragma mark -

@end
